from rest_framework import viewsets, status
from rest_framework.decorators import action, api_view, permission_classes
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
import logging
from ..services.conflict_service import ConflictService


logger = logging.getLogger('apps')


class BaseResponse:
    """基础响应类"""

    @staticmethod
    def success(data=None, message="操作成功"):
        return Response({
            "status": "success",
            "message": message,
            "data": data
        })

    @staticmethod
    def error(message="操作失败", status=status.HTTP_400_BAD_REQUEST):
        return Response({
            "status": "error",
            "message": message
        }, status=status)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def check_events_conflicts(request):
    """检查日程冲突并提供智能建议"""
    try:
        events_data = request.data.get('events', [])

        if not events_data:
            return BaseResponse.error("请提供日程数据")

        # 获取额外参数
        include_suggestions = request.data.get('include_suggestions', True)
        max_suggestions = request.data.get('max_suggestions', 5)
        check_internal_conflicts = request.data.get('check_internal_conflicts', True)

        # 记录请求信息
        logger.info(
            f"检查日程冲突: {len(events_data)}个日程, 包含建议: {include_suggestions}, 检查内部冲突: {check_internal_conflicts}")

        # 使用冲突服务检测冲突
        conflict_service = ConflictService()
        conflict_result = conflict_service.check_conflicts(request.user, events_data)

        # 如果不需要包含建议，移除建议数据以减少响应大小
        if not include_suggestions:
            for date_conflict in conflict_result.get('conflicts', []):
                for conflict in date_conflict.get('conflicts', []):
                    if 'suggestions' in conflict:
                        del conflict['suggestions']
                    if 'suggestions1' in conflict:
                        del conflict['suggestions1']
                    if 'suggestions2' in conflict:
                        del conflict['suggestions2']
        else:
            # 限制每个冲突的建议数量
            for date_conflict in conflict_result.get('conflicts', []):
                for conflict in date_conflict.get('conflicts', []):
                    if 'suggestions' in conflict and len(conflict['suggestions']) > max_suggestions:
                        conflict['suggestions'] = conflict['suggestions'][:max_suggestions]
                    if 'suggestions1' in conflict and len(conflict['suggestions1']) > max_suggestions:
                        conflict['suggestions1'] = conflict['suggestions1'][:max_suggestions]
                    if 'suggestions2' in conflict and len(conflict['suggestions2']) > max_suggestions:
                        conflict['suggestions2'] = conflict['suggestions2'][:max_suggestions]

        # 添加用户友好的摘要信息
        if conflict_result['has_conflicts']:
            severity_text = {
                "low": "轻微",
                "medium": "中度",
                "high": "严重"
            }

            summary = {
                'conflict_count': conflict_result['conflict_count'],
                'severity': severity_text.get(conflict_result['overall_severity'], "未知"),
                'message': f"检测到{conflict_result['conflict_count']}个日程冲突，整体冲突程度为{severity_text.get(conflict_result['overall_severity'], '未知')}。"
            }

            # 添加内部冲突和外部冲突的统计
            if 'has_internal_conflicts' in conflict_result and conflict_result['has_internal_conflicts']:
                internal_count = 0
                for date_conflict in conflict_result.get('conflicts', []):
                    if date_conflict.get('type') == 'internal':
                        internal_count += len(date_conflict.get('conflicts', []))

                summary['internal_conflict_count'] = internal_count
                summary['message'] += f" 其中{internal_count}个是待创建日程之间的冲突。"

            # 添加建议摘要
            if include_suggestions:
                suggestion_types = set()
                for date_conflict in conflict_result.get('conflicts', []):
                    for conflict in date_conflict.get('conflicts', []):
                        if 'suggestions' in conflict:
                            for suggestion in conflict.get('suggestions', []):
                                suggestion_types.add(suggestion['type'])
                        if 'suggestions1' in conflict:
                            for suggestion in conflict.get('suggestions1', []):
                                suggestion_types.add(suggestion['type'])
                        if 'suggestions2' in conflict:
                            for suggestion in conflict.get('suggestions2', []):
                                suggestion_types.add(suggestion['type'])

                suggestion_type_text = {
                    'reschedule': '调整时间',
                    'shorten': '缩短日程',
                    'next_day': '调整到次日',
                    'meal_time': '调整到用餐时间'
                }

                available_suggestions = [suggestion_type_text.get(t, t) for t in suggestion_types]
                if available_suggestions:
                    summary['available_suggestion_types'] = available_suggestions
                    summary['message'] += f"可用的调整方案包括: {', '.join(available_suggestions)}。"

            conflict_result['summary'] = summary

        return BaseResponse.success(conflict_result)
    except Exception as e:
        logger.error(f"检查日程冲突失败: {str(e)}")
        return BaseResponse.error(f"检查日程冲突失败: {str(e)}")